<?php
/**
 * 发布本地小说资源
 */
include_once('../lib/config.php');
include_once('../lib/Db.class.php');
include_once('../lib/Model.class.php');
include_once('../lib/Upyun.class.php');
include_once('../lib/function.php');

$redis = new Redis();  
$ret = $redis->connect("localhost","6379");  //php客户端设置的ip及端口
if(!$ret) die('redis connction faild');
$redis->auth(REDIS_PASS);
$redis->select(10);

$lsize = $redis->lSize('QISUU_LOCAL_FILE');
echo2($lsize . ' in QISUU_LOCAL_FILE', 'QISUU_POST_LOCAL');

$dir = QISUU_NEW . 'download/耽美纯爱/';
$count = 0;
if($lsize == 0) {
    $files = scandir($dir);
    foreach ($files as $k=>$file) {
        if(in_array($file, ['.', '..', '.DS_Store'])) continue;

        $new_file = preg_replace('/\s+/i', '_', $file);
        $new_file = str_replace('/', '_', $new_file);
        if($new_file != $file) {
            var_dump($file, $new_file);
            rename($dir . $file, $dir . $new_file);
            $file = $new_file;
        }

        $r = $redis->lPush('QISUU_LOCAL_FILE', json_encode($file));
        $count++;
    }
}

echo2($count . ' push QISUU_LOCAL_FILE', 'QISUU_POST_LOCAL');

$upyun = new UpYun(UPYUN_BUCKET_LPN, UPYUN_USER, UPYUN_PASS);

$no_files = [];
//从队列拿文件检查远程文件是否存在
while (true) {
    $stop = $redis->get('QISUU_QUEUE_STOP');
    if($stop) {
        echo2('stop', 'QISUU_POST_LOCAL'); break;
    }

    $data = $redis->lPop('QISUU_LOCAL_FILE');

    if(!$data) {
        echo2('QISUU_LOCAL_FILE empty', 'QISUU_POST_LOCAL'); break;
    }

    $filename = json_decode($data, true);

    if(!file_exists($dir . $filename)) {
        echo2("{$filename} cant find", 'QISUU_POST_LOCAL'); break;
    }

    if($redis->hExists('LNSUU_LOCAL_POSTED_HISTORY', $filename)) {
        continue;
    }

    try {
        $upfile = '/forum/books/耽美纯爱/' . $filename;

        echo2('getFileInfo:'.$upfile, 'QISUU_POST_LOCAL');
        $rsp = $upyun->getFileInfo($upfile);

        if(!$rsp) {
            $no_files[] = $filename;
            echo2('rsp:' . $filename . ' ' . count($no_files));
        }
        else {
            //加入发布队列
            if(!$redis->hExists('LNSUU_LOCAL_POSTED_HISTORY', $filename)) {
                $redis->lPush('LNSUU_LOCAL_POST_QUEUE', $filename);
                $redis->hSet('LNSUU_LOCAL_POSTED_HISTORY', $filename, 1);
            }
        }
    }
    catch(Exception $e) {
        $no_files[] = $filename;
        echo2('Exception:' . $e->getMessage() . " $filename " . count($no_files));
    }

    //break;
}

//发布文件
$users = file('./qisuu_all/lnsuu_user.txt');
while (true) {
    $stop = $redis->get('QISUU_QUEUE_STOP');
    if($stop) {
        echo2('stop', 'QISUU_POST_LOCAL'); break;
    }

    $filename = $redis->lPop('LNSUU_LOCAL_POST_QUEUE');

    if(!$filename) {
        echo2('LNSUU_LOCAL_POST_QUEUE empty', 'QISUU_POST_LOCAL');
        break;
    }

    $contents = [];
    if(stristr($filename, '.txt')) {
        $content = getFileLines($dir . $filename, 1, 50);
        $encode = mb_detect_encoding($content[1], ['ASCII','GB2312','GBK', 'BIG5', 'UTF-16LE', 'UTF-8']);
        if($encode != 'UTF-8') {
            foreach ($content as $value) {
                $contents[] = iconv('GBK', "UTF-8//IGNORE", $value);
            }
        } else {
            $contents = $content;
        }    
    }

    $downloadurl = 'http://lnpan.b0.upaiyun.com/forum/books/耽美纯爱/';
    $item =  $downloadurl . urlencode($filename);

    $title = str_replace('.', '', $filename) . '下载';
    $content = implode("\n", $contents);
    $content .= "\n\n下载地址：[url={$item}?_upd=true]{$filename}[/url]";

    $typeid = 12;
    $tags = '';

    shuffle($users);
    $user = $users[0];
    $user = preg_split('/\s+/', $user);
    $username = $user[0];
    $password = $user[1];

    $shell = "LC_ALL=en_US.UTF-8 /usr/bin/casperjs lnsuu_post.js '$title' '$content' '$typeid' '$username' '$password' '$tags'";
    echo2($shell, 'QISUU_POST_LOCAL');
    $result = shell_exec($shell);
    echo2('post result ' . $result, 'QISUU_POST_LOCAL');
    echo("\n\n");

    if(!stristr($result, 'published')) {
        $redis->lPush('LNSUU_LOCAL_POST_QUEUE', $filename);
        break;
    }
}

//上传文件
if($no_files) {
    print_r($no_files);

    foreach ($no_files as $k=>$filename) {
        try {
            echo2($k .'/'.count($no_files). ' uploading:' . $dir . $filename .' size:'.filesize($dir . $filename));

            $upfile = '/forum/books/耽美纯爱/' . $filename;
            $fh = fopen($dir . $filename, 'rb');
            $rsp = $upyun->writeFile($upfile, $fh, true);
            fclose($fh);

            if($rsp) {
                echo2('upload-success:' . $upfile);
            }
            else {
                echo2("error:{$upfile}".$rsp);
            }
        }
        catch(Exception $e) {
            echo2('Exception:' . $e->getMessage() . " $filename");
        }
    } 
}
